<?php

namespace addons\qingdongams\model;

use think\Model;
use think\Validate;
use traits\model\SoftDelete;

/**
 * 表单字段
 */
class FormField extends Model {
    use SoftDelete;

    const LEADS_TYPE = 'leads';
    const CUSTOMER_TYPE = 'customer';

    const CONTACTS_TYPE = 'contacts';
    const CONTRACT_TYPE = 'contract';
    const RECEIVABLES_TYPE = 'examine';
    const BUSINESS_TYPE = 'business';
    const SIGNIN_TYPE = 'signin';
	// 表名,不含前缀
	protected $name = 'qingdongams_form_field';
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

	public function getUpdatetimeAttr($value){
		return date('Y-m-d H:i',$value);
	}

    /**
     * 获取表单字段
     */
    public static function getFields($type){
        $fields=self::where(['types'=>$type,'list_show'=>1,'info_type'=>'main'])->select();
        $js=[];
        foreach ($fields as $v){
            if(in_array($v['field'],['name','num'])){//名称
                continue;
            }
            $d=[
                'field' => $v['field'],
                'title' => $v['name'],
                'operate' => 'like',
                'autocomplete' => false,
            ];
            if($v['form_type'] == 'Cascader'){
                $d['extend']='data-toggle="city-picker"';
            }else if($v['form_type'] == 'label'){//标签
                $d['formatter']='(false || function (value){
                            if(value){
                                let str_split=value.split(","),html="";
                                console.log(str_split)
                                $.each(str_split,function (index, item){
                                    let spab_split=item.split("^");
                                    html+= \'<div class="label" style="margin-left:5px;background: rgba(0, 82, 204, 0.1);color:\'+ spab_split[1] + \'">\'+ spab_split[0] + \'</div>\';
                                });
                                return html;
                            }else{
							    return value;
                            }
						})';
                if($v['setting']){
                    $set = json_decode($v['setting'],true);
                    $setting=[];
                    foreach ($set as $s){
                        foreach ($s['children'] as $c){
                            $setting[$c['la_va']]=$c['value'];
                        }
                    }
                }else{
                    $setting=[];
                }

                $d['operate'] = 'like';
                $d['searchList']=json_encode($setting,JSON_UNESCAPED_UNICODE);
            }else if($v['form_type'] == 'uploadImage'){//图片
                continue;
            }else if($v['form_type'] == 'uploadFile'){//文件
                continue;
            }else if($v['form_type'] == 'DatePicker' ){//日期
                $d['operate']='RANGE';
                $d['addclass']='datetimerange';
                $d['formatter']='Table.api.formatter.datetime';
                $d['extend']='data-locale="{format:\"YYYY-MM-DD\"}"';
            }else if($v['form_type'] == 'TimePicker' ){//时间
                $d['operate']='RANGE';
                $d['addclass']='datetimerange';
                $d['formatter']='Table.api.formatter.datetime';
            }else if($v['form_type'] == 'textarea'){//文本
                $d['operate']=false;
            }else if(in_array($v['form_type'],['select','checkbox','radio'])){//下拉
                $d['searchList']=json_encode(explode('|',$v['setting']),JSON_UNESCAPED_UNICODE);
            }else if(in_array($v['form_type'],['Rate'])){//分数
                $d['operate'] = '=';
                $d['searchList']=json_encode([1=>1,2=>2,3=>3,4=>4,5=>5],JSON_UNESCAPED_UNICODE);
            }else if($v['form_type'] == 'editor'){//编辑器
                $d['operate']=false;
            }else if($v['form_type'] == 'switch'){//开关
                $d['operate'] = '=';
                $d['searchList']=json_encode(['1'=>'启用','0'=>'关闭'],JSON_UNESCAPED_UNICODE);
                $d['formatter']='Table.api.formatter.status';
            } else if ($v['form_type'] == 'customer') {//关联客户
                $d['operate'] = '=';
                $d['addClass'] = 'selectpage';
                $d['visible'] = false;
                $d['extend'] = "data-source='qingdongams/customer/customer/index' data-field='name'";
            }  else if ($v['form_type'] == 'contact') {//关联联系人
                $d['operate'] = '=';
                $d['addClass'] = 'selectpage';
                $d['visible'] = false;
                $d['extend'] = "data-source='qingdongams/customer/contact/index' data-field='name'";
            }  else if ($v['form_type'] == 'contract') {//关联订单
                $d['operate'] = '=';
                $d['addClass'] = 'selectpage';
                $d['visible'] = false;
                $d['extend'] = "data-source='qingdongams/customer/contract/index' data-field='name'";
            } else if ($v['form_type'] == 'business') {//关联商机
                $d['operate'] = '=';
                $d['addClass'] = 'selectpage';
                $d['visible'] = false;
                $d['extend'] = "data-source='qingdongams/customer/business/index' data-field='name'";
            } else if ($v['form_type'] == 'staff') {//员工
                $d['operate'] = '=';
                $d['addClass'] = 'selectpage';
                $d['visible'] = false;
                $d['extend'] = "data-source='qingdongams/department/staff/index' data-field='name'";
            } else if ($v['form_type'] == 'department') {//关联部门
                $d['operate'] = '=';
                $d['addClass'] = 'selectpage';
                $d['visible'] = false;
                $d['extend'] = "data-source='qingdongams/department/group/index' data-field='name'";
            }

            $js[] = $d;
        }
        return json_encode($js,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 验证表单字段
     */
    public static function checkFields($types,&$params,$id=null)
    {
        switch ($types){
            case 'leads'://线索
                $model=new Leads();
                break;
            case 'customer'://客户
                $model=new Customer();
                break;
            case 'contract'://订单
                $model=new Contract();
                break;
            case 'contacts'://联系人
                $model=new Contacts();
                break;
            case 'business'://商机
                $model=new Business();
                break;
            case 'receivabels'://回款
                $model=new Receivables();
                break;
        }
        $fields=self::where(['types'=>$types,'info_type'=>'main'])->select();
        foreach ($fields as $v){
            //必填
            if($v['is_null'] == 1){
                if (!isset($params[$v['field']]) || empty($params[$v['field']])) {
                    return $v['name'] . '不能为空！';
                }
            }

            if(!empty($params[$v['field']])){
                $pattern = "/^(SELECT|INSERT|DELETE|UPDATE|DROP|ALTER)/i";
                if (preg_match($pattern, $params[$v['field']])) {
                    return $v['name'] . '输入有非法字符';
                }
            }

            if(!empty($params[$v['field']])){
                $pattern = "/^($|&|%)/i";
                if (preg_match($pattern, $params[$v['field']])) {
                    return $v['name'] . '输入有非法字符';
                }
            }




            //唯一
            if($v['is_unique'] == 1){
                if (!isset($params[$v['field']]) || empty($params[$v['field']])) {
                    continue;
                }
                $where=[];
                if(!empty($id)){
                    $where['id']=['neq',$id];
                }
                if(is_array($params[$v['field']])){
                    $params[$v['field']]=implode(',',$params[$v['field']]);
                }
                $where[$v['field']]=$params[$v['field']];
                if($model->where($where)->count() > 0){
                    return $v['name'] ."【{$params[$v['field']]}】". '已存在！';
                }
            }
            if($v['form_type'] == 'input-mobile' || $v['field'] == "mobile"){//手机号
                if (isset($params[$v['field']]) && $params[$v['field']]) {
                    if (!Validate::regex($params[$v['field']], "^1\d{10}$")) {
                        return $v['name'] ."【{$params[$v['field']]}】". '格式错误！';
                    }
                }
            }elseif($v['form_type'] == 'input-email' || $v['field'] == "email"){//邮箱
                if (isset($params[$v['field']]) && $params[$v['field']]) {
                    if (!Validate::is($params[$v['field']], "email")) {
                        return $v['name'] ."【{$params[$v['field']]}】". '格式错误！';
                    }
                }
            }elseif($v['form_type'] == 'editor'){//编辑器
                //编辑器提交时 会去除html 标签，重新获取值，不同表单有不同的提交名称
                if (isset($params[$v['field']]) && $params[$v['field']]) {
                    $list=['','row.','customer.','data.','contacts.','leads.'];
                    foreach ($list as $n) {
                        if (input($n . $v['field'], NULL, 'trim')) {
                            $params[$v['field']] = input($n . $v['field'], NULL, 'trim');
                            break;
                        }
                    }

                }
            }elseif($v['form_type'] == 'location' || $v['form_type'] == 'map'){//地理位置
                if($types == self::CUSTOMER_TYPE){//客户
                    if (isset($params[$v['field']]) && $params[$v['field']]) {
                        $params['address']=$params[$v['field']];
                        $params['address_detail']=$params[$v['field']];
                        $params['lat']=$params[$v['field'].'_lat'];
                        $params['lng']=$params[$v['field'].'_lng'];
                    }
                }
            }

        }
        return true;
    }

    /**
     * 获取搜索条件
     */
    public static function updateWhereField($types,$params){
        $fields=self::where(['types'=>$types,'info_type'=>'main'])->select();
        $where=[];
        foreach ($fields as $v){
            if(!isset($params[$v['field']]) || $params[$v['field']] === ''){
                continue;
            }

            if($v['form_type'] == 'uploadImage'){//图片
                continue;
            }else if($v['form_type'] == 'uploadFile'){//文件
                continue;
            }else if($v['form_type'] == 'DatePicker' ){//日期
                $times=explode(',',$params[$v['field']]);
                $where[$v['field']]=['between',$times ];
            }else if($v['form_type'] == 'TimePicker' ){//时间
                $times=explode(',',$params[$v['field']]);
                $where[$v['field']]=['between',$times ];
            }else if($v['form_type'] == 'textarea'){//文本
                continue;
            }else if(in_array($v['form_type'],['select','checkbox','radio'])){//
                $where[$v['field']]=$params[$v['field']];
            }else if(in_array($v['form_type'],['Rate'])){//星级
                $where[$v['field']]=$params[$v['field']];
            }else{
               $where[$v['field']]=['like',"%{$params[$v['field']]}%" ];
            }
        }
        return $where;
    }
}
